package com.lemon.cloud.oauth.support.mp;

import cn.hutool.core.util.StrUtil;
import com.lemon.cloud.oauth.support.base.OAuth2ResourceOwnerBaseAuthenticationConverter;
import com.lemon.cloud.security.enums.GrantTypeEnum;
import com.lemon.cloud.security.util.OAuth2EndpointUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.util.MultiValueMap;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author huangds
 * @date 2022-06-02
 *
 * 密码认证转换器
 */
public class OAuth2ResourceOwnerMpAuthenticationConverter extends OAuth2ResourceOwnerBaseAuthenticationConverter<OAuth2ResourceOwnerMpAuthenticationToken> {

	/**
	 * 支持密码模式
	 * @param grantType 授权类型
	 */
	@Override
	public boolean support(String grantType) {
		return GrantTypeEnum.WECHAT_MP_CODE.getType().equals(grantType);
	}

	@Override
	public OAuth2ResourceOwnerMpAuthenticationToken buildToken(Authentication clientPrincipal,
                                                                     Set requestedScopes, Map additionalParameters) {
		return new OAuth2ResourceOwnerMpAuthenticationToken(new AuthorizationGrantType(GrantTypeEnum.WECHAT_MP_CODE.getType()), clientPrincipal,
				requestedScopes, additionalParameters);
	}

	/**
	 * 校验扩展参数 密码模式密码必须不为空
	 * @param request 参数列表
	 */
	@Override
	public void checkParams(HttpServletRequest request) {
		HashMap<String, Boolean> params = GrantTypeEnum.WECHAT_MP_CODE.getParams();
		if (params.isEmpty()){
			return;
		}
		MultiValueMap<String, String> parameters = OAuth2EndpointUtils.getParameters(request);
		for (Map.Entry<String, Boolean> entry : params.entrySet()) {
			//必填字段
			if (entry.getValue()){
				String key = entry.getKey();
				String reqVal = parameters.getFirst(key);
				if (StrUtil.isEmpty(reqVal)) {
					OAuth2EndpointUtils.throwError(OAuth2ErrorCodes.INVALID_REQUEST, key,
							OAuth2EndpointUtils.ACCESS_TOKEN_REQUEST_ERROR_URI);
				}
			}
		}
	}

}
